#!/command/with-contenv bashio
# vim: ft=bash
# shellcheck shell=bash
# ==============================================================================
# Pre-start initialization of MariaDB service
# ==============================================================================
MARIADB_DATA=/data/databases
NEW_INSTALL=false

if ! bashio::fs.directory_exists "${MARIADB_DATA}"; then
    NEW_INSTALL=true
fi

# Save variables
echo -n "${MARIADB_DATA}" > /var/run/s6/container_environment/MARIADB_DATA
echo -n "${NEW_INSTALL}" > /var/run/s6/container_environment/NEW_INSTALL

# Redirect log output
mkdir -p "${MARIADB_DATA}"
rm -f "${MARIADB_DATA}/mariadb.err"
ln -s /proc/1/fd/1 "${MARIADB_DATA}/mariadb.err"

# Init mariadb
if bashio::var.true "${NEW_INSTALL}"; then
    bashio::log.info "Create a new mariadb"
    mysql_install_db --user=root --datadir="${MARIADB_DATA}" --skip-name-resolve --skip-test-db > /dev/null
else
    bashio::log.info "Using existing mariadb"
fi
